//
//  UIHeartbeatView.swift
//  TTCOM
//
//  Created by Toj on 3/30/23.
//

import UIKit

private let kHeartbeatAnimationKey = "kHeartbeatAnimationKey"
private var defaultScope = 0.95
private var defaultDuration: TimeInterval = 1
/*
 * 带有流光效果View
 */
public class UIHeartbeatView: UIView {
    
    public var repeatCount = MAXFLOAT
    
    /** 呼吸变化幅度, 默认0.95 */
    public var scope = defaultScope
    /** 单次效果持续时间, 默认1s */
    public var duration = defaultDuration
    
    private var isHeartBeating = false
    private weak var gradientLayer: CALayer?
    
    public override init(frame: CGRect) {
        super.init(frame: frame)
        isUserInteractionEnabled = false
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

public extension UIHeartbeatView {
    
    func startHeartbeatAnimation() {
        guard !isHeartBeating else { return }
        isHeartBeating = true
        
        let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
        let scope_ = scope > 0 ? scope : defaultScope
        let duration_ = duration > 0 ? duration : defaultDuration
        scaleAnimation.values = [1, scope_, 1]
        
        scaleAnimation.duration = duration_
        scaleAnimation.repeatCount = repeatCount
        layer.add(scaleAnimation, forKey: kHeartbeatAnimationKey)
    }
    
    func stopHeartbeatAnimation() {
        isHeartBeating = false
        layer.removeAnimation(forKey: kHeartbeatAnimationKey)
    }
}

extension UIHeartbeatView: CAAnimationDelegate {
    
    public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        stopHeartbeatAnimation()
    }
}
